package com.zx.flow.api.listener;

import com.zx.flow.api.execute.common.ResponseStatusAnno;
import com.zx.flow.api.execute.response.Response;
import com.zx.flow.api.listener.request.FlowOperator4Listener;
import com.zx.flow.api.util.AssertUtil;
import com.zx.flow.api.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/flow/client/event")
@Tag(name = "流程事件")
@ResponseStatusAnno
@Slf4j
public class FlowEventController {

    @Value("${luckflow.token.secretId:test-key}")
    private String secretId;

    @Value("${luckflow.token.secretKey:test-value}")
    private String secretKey;

    @PostMapping("/receive")
    @Operation(summary = "接收事件")
    public Response<String> receive(@RequestBody @Valid FlowEvent event, HttpServletRequest request) {
        try {
            //this.verify(request);
            FlowEventRegister.doListener(event);
            return Response.success("");
        } catch (Exception e) {
            log.error("luckFlow接收事件异常", e);
            return Response.fail("luckFlow接收事件异常:" + e.getMessage());
        }
    }

    @PostMapping("/getOperators")
    @Operation(summary = "获得操作人")
    public Response<List<FlowOperator4Listener>> getOperators(@RequestBody @Valid FlowEvent event,
            HttpServletRequest request) {
        try {
            //this.verify(request);
            return Response.success(FlowEventRegister.getOperators(event));
        } catch (Exception e) {
            log.error("luckFlow 获得操作人 异常", e);
            return Response.fail("luckFlow 获得操作人 异常:" + e.getMessage());
        }
    }


    private void verify(HttpServletRequest request) {
        String jwt = request.getHeader(JWTUtil.JWT_KEY);
        String secretId = request.getHeader(JWTUtil.SECRETID_KEY);
        AssertUtil.checkSecurity(jwt, "token校验失败, token为空");
        AssertUtil.checkSecurity(secretId, "token校验失败, secretId为空");
        AssertUtil.checkEques(this.secretId, secretId, "token校验失败, secretId非法");

        String accountCode = JWTUtil.verifyAndGet(secretId, secretKey, jwt, String.class);
        AssertUtil.checkSecurity(accountCode, "token校验失败, 用户信息为空");
    }
}
